
<template>
  <div class="tvmCYQRTZ">
    <basic-container>
      <avue-crud
        ref="tvmCYQRTZ"
        :option="option"
        :table-loading="listLoading"
        :data="list"
        :permission="permissionList"
        :page.sync="page"
        @search-change="handleFilter"
        @selection-change="selectionChange"
        @refresh-change="refreshChange"
        @on-load="refreshChange">
        <template slot-scope="scope" slot="menuRight">
          <el-button type="primary" v-if="permissionList.multiAudit" size="mini" @click="myAdd">添加</el-button>
          <el-button type="primary" v-if="permissionList.multiAudit" size="mini" @click="multiAudit">批量审批</el-button>
          <el-button type="primary" v-if="permissionList.sendStatusUpdate" size="mini" @click="sendStatusUpdate">下发</el-button>
          <el-button type="primary"  size="mini" v-permission="permissionList.handleDelete" @click="handleDelete">删除</el-button>

        </template>
        <template slot-scope="scope" slot="lineCodeSearch">
          <el-select v-model="searchForm.lineCode" placeholder="请选择" style="width: 150px" @change="changeLine" clearable>
            <el-option
              v-for="(item,index) in lineCodes"
              :key="index"
              :label="item.name"
              :value="item.code">
            </el-option>
          </el-select>
        </template>
        <template slot-scope="scope" slot="stationCodeSearch">
          <el-select v-model="searchForm.stationCode" placeholder="请选择" style="width: 150px" clearable @change="changeStation">
            <el-option
              v-for="(item,index) in stationCodes"
              :key="index"
              :label="item.name"
              :value="item.code">
            </el-option>
          </el-select>
        </template>
        <template slot-scope="scope" slot="conductorPersonNameSearch">
<!--          <el-select v-model="searchForm.conductorPersonName" placeholder="请选择" style="width: 150px" clearable>-->
<!--            <el-option-->
<!--              v-for="(item,index) in conductorPersonNames"-->
<!--              :key="index"-->
<!--              :label="item.nikename"-->
<!--              :value="item.nikename">-->
<!--            </el-option>-->
<!--          </el-select>-->
        </template>
        <template slot="search" slot-scope="{row,size}">
<!--          <el-form-item label="差异条件" style="width: 300px" >-->
<!--            <el-select v-model="searchForm.isDifferenceAmount" placeholder="请选择">-->
<!--              <el-option label="长款" value="1"></el-option>-->
<!--              <el-option label="短款" value="2"></el-option>-->
<!--            </el-select>-->
<!--          </el-form-item>-->
        </template>

        <template slot="searchMenu" slot-scope="{row,size}">
          <el-button :size="size" @click="()=>{setSearchFiledsEmpty(row);setSearchFiledsEmpty(searchForm);getList()}" icon="el-icon-delete">清空</el-button>
        </template>
        <template slot-scope="scope" slot="menu">
<!--          <el-button type="primary" v-if="false" size="small" @click="handleDownload(scope.row)">下载附件</el-button>-->
          <el-button type="text" size="small"
                     v-if="scope.row.sendStatus=='1'" plain @click="myEdit(scope.row)">编辑</el-button>
          <el-button type="text" size="small"
                     plain @click="previewEditor(scope.row)">预览</el-button>
<!--          <el-button type="text" size="small" v-if="scope.row.sendStatus==''"></el-button>-->
        </template>
      </avue-crud>

      <prev ref="prev" v-if="dialogVisibleprev"></prev>

      <el-dialog
        title="审批"
        :visible.sync="dialogVisibleAppealReply"
        width="30%"
      >
        <span>审批意见：</span>
        <el-input type="textarea" v-model="param.appealReply" maxlength="50" placeholder=""></el-input>
        <span slot="footer" class="dialog-footer">
          <el-button type="primary" @click="setAppealReply(11)">通过</el-button>
          <el-button  @click="setAppealReply(12)">加入补款</el-button>
        </span>
      </el-dialog>
      <open-dialog title="添加" :DialogVisible.sync="addVisableDialog">
        <el-form label-width="60px">
          <avue-form
            ref="form"
            v-model="formData"
            :option="tableOptionAdd"
          >
            <template slot-scope="scope" slot="lineCode">
              <el-select v-model="formData.lineCode" placeholder="请选择" style="width: 150px" @change="changeLine" clearable filterable>
                <el-option
                  v-for="(item,index) in lineCodes"
                  :key="index"
                  :label="item.name"
                  :value="item.code">
                </el-option>
              </el-select>
            </template>
            <template slot-scope="scope" slot="stationCode">
              <el-select v-model="formData.stationCode" placeholder="请选择" style="width: 150px" clearable @change="changeStation2" filterable>
                <el-option
                  v-for="(item,index) in stationCodes"
                  :key="index"
                  :label="item.name"
                  :value="item.code">
                </el-option>
              </el-select>
            </template>
            <template slot-scope="scope" slot="conductorPersonName">
              <el-select v-model="formData.conductorPersonName" placeholder="请选择" style="width: 150px"
                         @change="conductorPersonNameChange"
                         clearable filterable allowCreate>
                <!--                     @change="(v)=>{formData.conductorPersonName=v.nikename;formData.conductorPersonCode=v.userCode}"-->

                <el-option
                  v-for="(item,index) in conductorPersonNames"
                  :key="index"
                  :label="item.nikename"
                  :value="item">
                </el-option>
              </el-select>
            </template>
            <template slot-scope="scope" slot="conductorPersonCode">
              <el-select v-model="formData.conductorPersonCode" placeholder="请选择" style="width: 150px" clearable allowCreate  filterable>
                <el-option
                  v-for="(item,index) in conductorPersonNames"
                  :key="index"
                  :label="item.userCode"
                  :value="item.userCode">
                </el-option>
              </el-select>
            </template>
            <template slot-scope="scope" slot="equipmentNumber">
              <el-select v-model="formData.equipmentNumber" placeholder="请选择" style="width: 150px"   filterable allowCreate>
                <el-option
                  v-for="(item,index) in conductorPersonNames"
                  :key="index"
                  :label="item.deviceOperateNo"
                  :value="item.deviceOperateNo">
                </el-option>
              </el-select>
            </template>
	    <template slot-scope="scope" slot="tvmCode">
              <el-select v-model="formData.tvmCode" placeholder="请选择" style="width: 150px"   filterable allowCreate>
                <el-option
                  v-for="(item,index) in tvmCodes"
                  :key="index"
                  :label="item.tvmCode"
                  :value="item.tvmCode">
                </el-option>
              </el-select>
            </template>
          </avue-form>

          <div class="bottom-menu-input">
            <el-button type="primary" @click="save()">保存</el-button>
            <el-button @click="addVisableDialog = false"
            >取消</el-button
            >
          </div>
        </el-form>
      </open-dialog>

      <open-dialog title="编辑" :DialogVisible.sync="editVisableDialog">
        <el-form label-width="60px">
          <avue-form
            ref="form"
            v-model="formData"
            :option="tableOptionAdd"
          >
            <template slot-scope="scope" slot="lineCode">
              <el-select v-model="formData.lineCode" placeholder="请选择" style="width: 150px" @change="changeLine" clearable filterable>
                <el-option
                  v-for="(item,index) in lineCodes"
                  :key="index"
                  :label="item.name"
                  :value="item.code">
                </el-option>
              </el-select>
            </template>
            <template slot-scope="scope" slot="stationCode">
              <el-select v-model="formData.stationCode" placeholder="请选择" style="width: 150px" clearable @change="changeStation2" filterable>
                <el-option
                  v-for="(item,index) in stationCodes"
                  :key="index"
                  :label="item.name"
                  :value="item.code">
                </el-option>
              </el-select>
            </template>
            <template slot-scope="scope" slot="conductorPersonName">
              <el-select v-model="formData.conductorPersonName" placeholder="请选择" style="width: 150px"
                         @change="conductorPersonNameChange"
                         clearable filterable allowCreate>
                <!--                     @change="(v)=>{formData.conductorPersonName=v.nikename;formData.conductorPersonCode=v.userCode}"-->

                <el-option
                  v-for="(item,index) in conductorPersonNames"
                  :key="index"
                  :label="item.nikename"
                  :value="item">
                </el-option>
              </el-select>
            </template>
            <template slot-scope="scope" slot="conductorPersonCode">
              <el-select v-model="formData.conductorPersonCode" placeholder="请选择" style="width: 150px" clearable allowCreate  filterable>
                <el-option
                  v-for="(item,index) in conductorPersonNames"
                  :key="index"
                  :label="item.userCode"
                  :value="item.userCode">
                </el-option>
              </el-select>
            </template>
            <template slot-scope="scope" slot="equipmentNumber">
              <el-select v-model="formData.equipmentNumber" placeholder="请选择" style="width: 150px"   filterable allowCreate>
                <el-option
                  v-for="(item,index) in conductorPersonNames"
                  :key="index"
                  :label="item.deviceOperateNo"
                  :value="item.deviceOperateNo">
                </el-option>
              </el-select>
            </template>
	    <template slot-scope="scope" slot="tvmCode">
              <el-select v-model="formData.tvmCode" placeholder="请选择" style="width: 150px"   filterable allowCreate>
                <el-option
                  v-for="(item,index) in tvmCodes"
                  :key="index"
                  :label="item.tvmCode"
                  :value="item.tvmCode">
                </el-option>
              </el-select>
            </template>
          </avue-form>

          <div class="bottom-menu-input">
            <el-button type="primary" @click="audit()">保存</el-button>
            <el-button @click="editVisableDialog = false"
            >取消</el-button
            >
          </div>
        </el-form>
      </open-dialog>
      <approve ref="approve" v-if="approveDialogVisible"></approve>
    </basic-container>
  </div>
</template>

<script>
import {getOption,
  fetchList,
  getObj,
  addObj,
  putObj,
  delObj,
  sendStatusUpdate,
  setAppealReply,tableOptionAdd} from '@/api/subwayRat/swAuTvm/tvmCYQRTZ'
import {mapGetters} from 'vuex'
import prev
  from "@/views/stationTiecketManager/xianWngCJXXQR/tvmPiaoKuanCY/tvmPiaoKuanCYTZ/prev.vue";
import approve from "@/views/subwayRat/conductorDifferences/shouPiaoYuanCYQRTZ/approve.vue";
import {
  fenExYuangettoFixed,
  getgetStationCodes,
  getLineAndStationByCode, getLineCodes,getSwPmTvmCodeList,
  getSysUserToLS,
  setSearchFiledsEmpty
} from "@/api/subwayRat/commonCheck";

export default {
  name: 'tvmCYQRTZ',
  components:{
    prev,
    approve
  },
  data() {
    return {
      addVisableDialog: false,
      listLoading: true,
      searchForm:{
        lineCode:'9',
        stationCode:''
      },
      formData:[],
      dialogVisibleAppealReply:false, //申诉回复
      approveDialogVisible:false,//打开审批界面
      dialogVisibleprev:false,//预览
      editVisableDialog: false,//编辑
      tableData: [],
      option: {},
      lineCodes:[],
      stationCodes:[],
      conductorPersonNames:[],
      tvmCodes:[],
      tableOptionAdd: tableOptionAdd,
      page: {
        total: 0, // 总页数
        currentPage: 1, // 当前页数
        pageSize: 20 // 每页显示多少条
      },
      param:{
        replyPeriod:3,//回复期限
        appealReply:'',//申诉回复
      },
      list : []
    }
  },
  computed: {
    ...mapGetters(['permissions']),
    permissionList() {
      return {
        handleDelete: this.vaildData(
          this.permissions.tvmCYQRTZ_Delete,
          false
        ),
        multiAudit: this.vaildData(
          this.permissions.tvmCYQRTZ_multi_audit,
          false
        ),
        sendStatusUpdate: this.vaildData(
          this.permissions.tvmCYQRTZ_send_status_update,
          false
        ),
      };
    }
  },
  created() {
    this.option=getOption();
    this.changeLine("9")
  },
  methods: {
    setSearchFiledsEmpty,
    getList() {
      this.listLoading = true;
      Object.assign(this.searchForm,this.page);
      this.searchForm.combinStatus=0;
      fetchList(this.searchForm).then(response => {
        this.list = response.data.data
        this.page.total = response.data.total
        this.listLoading = false
      });
    },

    setAppealReply(auditSate){//申诉回复
      if(this.selectKeys.length<=0){
        this.$message.warning("请选择要设置的数据！");
        return;
      }
      for(let i=0;i<this.selectKeys.length;i++) {
        if ("9" != this.selectKeys[i].auditSate) {
          this.$message.warning("勾选数据中存在审批状态非部门审核通过的数据！");
          return
        }
      }
      if(this.param.appealReply==null || this.param.appealReply=='' || this.param.appealReply==undefined){
        this.$message.warning("请填写内容！");
        return;
      }
      setAppealReply({auditSate:auditSate,appealReply:this.param.appealReply,ids:this.selectKeyVals.join(",")}).then(res=>{
        if(res.data.code==0){
          this.$message.success("操作成功！");
          this.getList();
          this.dialogVisibleAppealReply=false;
        }else{
          this.$message.error("操作失败！");
        }
      }).catch(e=>{
        this.$message.error("操作失败！");
      })
    },
    changeLine2(v){ //改变线路时
      getgetStationCodes(v).then(res=>{
        this.stationCodes=res;
      });
    },
    changeStation2(v){
      let p = {
        line_code : this.formData.lineCode,
        station_code : v,
        belong_to_line:0
      };
      getSysUserToLS(p).then((res)=>{
        this.conductorPersonNames=res.data.data;
      });
       getSwPmTvmCodeList({lineCode:this.formData.lineCode, stationCode:v}).then(r=>{
          this.tvmCodes=r.data;
       });
    },
    myEdit(row){
      getObj(row.id)
        .then((response) => {
          let res = response.data.data;
          this.formData = res;
          Object.assign(this.formData,row);
          this.changeLine2(row.lineCode);
          this.changeStation2(row.stationCode);
          this.$nextTick(() => {
            this.formatterAmount(this.formData,true);
          })
        })
        .then(() => {
          this.editVisableDialog = true;
        });
    },
    formatterAmount(row,isYuan){ //格式化钱
      if(isYuan){
        row.differenceAmount=fenExYuangettoFixed(row,'differenceAmount');
      }
      return row;
    },
    previewEditor(row){
      this.dialogVisibleprev=true;
      this.$nextTick(()=>{
        this.$refs.prev.dialogVisible=true;
        this.$refs.prev.recallShow(row,this);
      })
    },
    audit: function () {
      if (
        this.formData.lineCode == "" ||
        this.formData.stationCode == "" ||
        this.formData.conductorPersonName == "" ||
        this.formData.tvmCode == "" ||
        this.formData.recordTime == null ||
        this.formData.differenceAmount == null
      ) {
        this.$message.error(
          "线路、站点、售票员、TVM编号、收入日期、差异金额为必填项！不能为空"
        );
        return;
      }
      this.formatterAmount(this.formData,false);
      putObj(this.formData)
        .then((data) => {
          this.$message.success("修改成功");
          this.editVisableDialog = false;
          this.getList(this.page);
          done();
        })
        .catch(() => {});
    },
    myAdd() {
      for (var i in this.formData) {
        this.formData[i] = "";
      }
      this.addVisableDialog = true;
    },
    save: function () {
      console.log(JSON.stringify(this.formData))
      if (
        this.formData.lineCode == "" ||
        this.formData.stationCode == "" ||
        this.formData.conductorPersonName == "" ||
        this.formData.tvmCode == "" ||
        this.formData.recordTime == null ||
        this.formData.differenceAmount == null
      ) {
        this.$message.error(
          "线路、站点、售票员、TVM编号、收入日期、差异金额为必填项！不能为空"
        );
        return;
      }
      addObj(this.formData)
        .then((data) => {
          this.$message.success("添加成功");
          this.addVisableDialog = false;
          this.getList(this.page);
          done();
        })
        .catch(() => {});
    },
    //操作批量审批按钮
    multiAudit(){
      if(this.selectKeys.length<=0){
        this.$message.warning("请选择要审批的数据！");
        return;
      }
      for(let i=0;i<this.selectKeys.length;i++){
        if(this.selectKeys[i].sendStatus==1 ){
          this.$message.warning("请选择已下发数据！");
          return;
        }
        if ("9" != this.selectKeys[i].auditSate) {
          this.$message.warning("勾选数据中存在审批状态非部门审核通过的数据！");
          return
        }
      }
      let statusIds = [];
      for(let i=0;i<this.selectKeys.length;i++){
        if(this.selectKeys[i].appealStatus==1 ){
          statusIds.push(this.selectKeys[i].appealStatus);
        }
      }
      if(statusIds.indexOf('1')>-1){//1代表未申诉
        this.$confirm("所选数据有售票员还未确认，是否要审批？", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }).then(() => {
          this.dialogVisibleAppealReply=true;
        });
      }else{
        this.dialogVisibleAppealReply=true;
      }
    },

    async sendStatusUpdate(){
      if(this.selectKeys.length<=0){
        this.$message.warning("请选择要设置的数据！");
        return;
      }
      for(let i=0;i<this.selectKeys.length;i++){
        if(this.selectKeys[i].sendStatus==2){
          this.$message.warning("请选择未下发的数据！");
          return;
        }
      }
      let messageLSList = [];
      for(let i=0;i<this.selectKeys.length;i++){
        let data = await getLineAndStationByCode({"lineCode":this.selectKeys[i].lineCode, "code":this.selectKeys[i].stationCode});
        messageLSList.push({
          "content":"车站：" + data.data[0].name,
          "lineCode":this.selectKeys[i].lineCode,
          "stationCode":this.selectKeys[i].stationCode
        })
      }
      let p = {
        messageLSList:JSON.stringify(messageLSList),
        //title:this.$store.getters.tag.label,
        title:'TVM票款差异确认通知',
        msgType:"下发",
        type:"tvmCYQRTZ_001",
        ids:this.selectKeyVals.join(','),
        sendStatus:2
      };
      sendStatusUpdate(p).then(res=>{
        if(res.data.code==0){
          this.$message.success("操作成功！");
          this.getList();
        }else{
          this.$message.error("操作失败！");
        }
      }).catch(e=>{
        this.$message.error("操作失败！");
      })
    },

    //删除
    handleDelete: function () {
      if (this.selectKeys.length === 0) {
        this.$message.error('请选择要删除的数据！');
        return;
      }
      this.$confirm("是否需要删除?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "success"
      }).then(() => {
        delObj({ids: this.selectKeyVals})
          .then(data => {
            if (data.data.code == "0") {
              this.$message.success("删除成功");
            }
            this.getList(this.page);
            done();
          })
          .catch(() => {
            loading();
          });
      });
    },

    selectionChange(list){
      this.selectKeys=list;
      this.selectKeyVals=[];
      for(let i=0;i<list.length;i++){
        this.selectKeyVals.push(list[i].id);
      }
    },

    handleFilter(params, done) {
      Object.assign(this.searchForm,params);
      this.getList()
      done()
    },

    rowDel: function (row, index) {
      var _this = this
      this.$confirm('是否确认删除ID为' + row.id, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(function () {
        return delObj(row.id)
      }).then(data => {
        _this.$message.success('删除成功')
        this.getList(this.page)
      })
    },
    handleUpdate: function (row, index, done,loading) {
      putObj(row).then(data => {
        this.$message.success('修改成功')
        done()
        this.getList(this.page)
      }).catch(() => {
        loading();
      });
    },
    handleSave: function (row, done,loading) {
      addObj(row).then(data => {
        this.$message.success('添加成功')
        done()
        this.getList(this.page)
      }).catch(() => {
        loading();
      });
    },
    searchChange(form) {
      this.searchForm = form
      this.getList(this.page, form)
    },
    refreshChange(){
      this.getList()
    },

    conductorPersonNameChange(selectedValue){
      console.log(selectedValue)
      if (selectedValue != null &&
        selectedValue != '' &&
        selectedValue.nikename == undefined) {
        this.formData.conductorPersonName=selectedValue
        this.formData.conductorPersonCode='';
        this.formData.equipmentNumber=''
        return
      }
      this.formData.conductorPersonName=selectedValue.nikename;
      this.formData.conductorPersonCode=selectedValue.userCode;
      this.formData.equipmentNumber=selectedValue.deviceOperateNo

    },

    changeLine(v){ //改变线路时
      getgetStationCodes(v).then(res=>{
        this.stationCodes=res;
        this.searchForm.stationCode='';
        this.formData.stationCode='';
        this.formData.conductorPersonName='';
        this.formData.conductorPersonCode='';
        this.formData.equipmentNumber='';//设备操作号增加置空  20240228
	this.formData.tvmCode='';
      })
    },

    changeStation(v){
      getSysUserToLS({lineCode:this.searchForm.lineCode, stationCode:v}).then((res)=>{
        this.conductorPersonNames=res.data.data;
      });

      getSwPmTvmCodeList({lineCode:this.searchForm.lineCode, stationCode:v}).then(r=>{
          this.tvmCodes=r.data;
       });
     },
  },
  mounted() {
    getLineCodes().then(res=>{ //获取线路
      this.lineCodes=res;
    });
  }
}
</script>
<style lang="scss">
  .bottom-menu-input {
    margin-top: 30px;
    text-align: center;
  }
</style>
